define([ "jquery","glable_mask","comm","site_tip","plugin/jquery.cookie",
         "plugin/tree/tree.jquery","mustache.min","text!/static/page/file_move.html","text!/static/page/folder_item.html","css!/static/css/move.css","css!/static/js/jquery/tree/jqtree.css"],
		function( $,Glable_mask,comm,Site_tip,JCookie,tree,Mustache,fileMoveTpl,folderItemTpl) {
	
	var site_tip = new Site_tip();
	
	function Move(datas,delFun) {
		this.datas = datas;
		this.delFun = delFun;
		this.glable_mask = null;
		this._id = null;
		
		this.initCss();
	}
	/**
	 * 重新设定新建文件夹名字索引最大数
	 */
	function resetCreateNewFolderNameMax(cb){
		var curFolderDom = $("#folderPath").find("[uuid][haslast]");
		var params={};
		if(curFolderDom.length>0)
		{
			params.file_id = curFolderDom.attr("uuid");
		}
		$.getJSON("/files/get_new_folder_num",params,function(jsonData){
			//console.log(jsonData);
			if(jsonData.success){
				var arr = jsonData.data;
				$("#waterfall").attr("defindMax",parseInt(arr.defindMax));
			}
			if($.isFunction(cb))
			{
				cb(jsonData);
			}
		});
	};
	Move.prototype.initCss = function (){
		//comm.loadCss("/static/css/move.css");
		//comm.loadCss("/static/js/jquery/tree/jqtree.css");
		
	}
	
	Move.prototype.init = function (){
		var that = this;
		that.glable_mask = new Glable_mask();
		that.glable_mask.add($(fileMoveTpl),true);
		that.glable_mask.update();

		if(comm.lessThenIE(9) && comm.isIE()){
			$("#fileMove").find(".title").css("border-bottom","1px solid #c9c9c9");
			$("#fileMove").find(".btnPanel").height(57);
		}

		//$("#waterfall").attr("defindMax", 0);
		$("#fileMove").find("a.btn").each(function(){
			$(this).attr("disabled",true);
		});
		//$("#fileMoveList").html("xxxxxxxxxx");
		//console.log($("#fileMoveList"));
		$("#fileMoveList").tree({autoOpen:true,selectable: true});
		$('#fileMoveList').addClass("loading")/*.css("visibility","hidden")*/.attr("defindMax",0);
		//$('#fileMoveList').tree('selectNode', 0);
		//$('#fileMoveList').css("visibility","visible");
		/*setTimeout(function(){
		 console.log($('#fileMoveList').tree('getNodeById', "0"));
		 },1000);*/
		/*this._id = setTimeout(function(){
		 var node = $('#fileMoveList').tree('getNodeById', "0");
		 $('#fileMoveList').tree('selectNode', node);
		 $('#fileMoveList').css("visibility","visible");
		 }, 500);*/

		$('#fileMoveList').bind(
			'tree.init',
			function() {
				//$('#fileMoveList').css("visibility","visible");
				// initializing code
				$('#fileMoveList').removeClass("loading");
				var tree = $(this);
				var node = tree.tree('getNodeById', 0);
				tree.tree('selectNode', node);
			}
		);
		that._bindUI();
		return false;
	};
    Move.prototype.disableOkBtn = function(loading)
	{
		var okBtn = $("#fileMove").find(".btn.ok");
		okBtn.attr("disabled",true).text(loading?"保存中...":"保存");
	};
	Move.prototype.disableAddBtn = function()
	{
		var okBtn = $("#fileMove").find(".btn.add");
		okBtn.attr("disabled",true);
	};
	Move.prototype.enableOkBtn = function()
	{
		var okBtn = $("#fileMove").find(".btn.ok");
		okBtn.attr("disabled",false).text("保存");
	};
	Move.prototype.enableAddBtn = function()
	{
		var okBtn = $("#fileMove").find(".btn.add");
		okBtn.attr("disabled",false);
	};
	Move.prototype._bindUI = function (){
		var that = this;
		var selectId = "0";
		var isCom = true;
		
		$("#fileMove").off("click",".close");
		$("#fileMove").find(".close").click(function(e) {
			comm.stopEvent(e);
			//console.log(that.datas);

			resetCreateNewFolderNameMax();
			that.glable_mask.remove();
			that.glable_mask = null;
			return false;
		});
		
		$("#fileMove").off("click",".ok");
		$("#fileMove").on("click",".ok",function(e){
			var id = selectId;
			//console.log("first:"+$("#waterfall").attr("defindMax"));
			//var oldDefindMax = $("#waterfall").attr("defindMax");
			/*$.getJSON("/files/get_new_folder_num",{file_id:that.datas[0]},function(jsonData){
				if(jsonData.ret == -1){
					var arr = jsonData.data;
					$("#waterfall").attr("defindMax",parseInt(arr.defindMax)+1);
					console.log(arr.defindMax);
				}
			});*/
			that.disableOkBtn(true);
			that.disableAddBtn();
			resetCreateNewFolderNameMax(function(){
				$("body").one("networkError",function(){
					that.enableAddBtn();
					that.enableOkBtn();
				});
				$.post("/files/move",{files:that.datas.join(","),folder_id:id},function(jsonData){
					that.enableAddBtn();
					that.enableOkBtn();
					if(jsonData.success){
						that.delFun();
						that.glable_mask.remove();
						that.glable_mask = null;
						var len = $("#mypage").find(".icon-checkbox:visible").size();
						var selLen = $("#mypage").find(".icon-checkbox.hover:visible").size();

						if(selLen>0 && len == selLen){
							$("#selAllFiles").find(".icon-checkbox").addClass("hover");
						}else{
							$("#selAllFiles").find(".icon-checkbox").removeClass("hover");
						}
						site_tip.setContent("移动成功");
					}
					else
					{
						site_tip.setContent(jsonData.message,true);
					}

				}, "json");
			});

			return false;
		});
		
		$("#fileMove").off("click",".add");
		$("#fileMove").on("click",".add",function(e){
			if(!isCom){
				return;
			}
			isCom = false;
			var parent_node = $('#fileMoveList').tree('getNodeById', selectId);
			 
			var label;
			var uuid = comm.NewGuid();
			var defindMax = $('#fileMoveList').attr("defindMax");
			//console.log(defindMax);
			if(defindMax == 0){
				label = "新建文件夹";
			}else{
				label = "新建文件夹("+ defindMax+")";
			}

			$('#fileMoveList').tree(
                'appendNode',
                {
                    label: label,
                    id: uuid
                },
                parent_node
            );
			
			 $('#fileMoveList').tree('openNode', parent_node);
			 var node = $('#fileMoveList').tree('getNodeById', uuid);
			 var element = $(node.element);
			 element.find("span").html("<input class='edit-txt' maxlength='85' type='text' value='"+label+"'>");
			 
			 var input = $(element).find("input");
			 input.select();
			 input.val(label);
			 input.on("keydown",function(e)
			 {
				 if(e.keyCode==13)
				 {
					 $(this).blur();
				 }
				 e.stopPropagation();
			 });
			 input.on("blur",function(e){
				 var inputThat = this;
				 
				 var folderName = $.trim($(this).val());
				 
				 if(folderName.length == 0){
					site_tip.setContent("文件名不能为空",true,false);
					$(this).focus();
					return;
				 }
				 
				 if(!comm.checkSpecialStr(folderName)){
					var err_msg = "文件夹名不能包含 \\ / : * ? \" < > |"; 
					site_tip.setContent(err_msg,true,false);
					return;
				 }
				 
				 var uuidtemp = selectId;
				 if(uuidtemp == "0"){
					 uuidtemp = "";
				 }
				 
				 $.getJSON("/files/add_folder",{uuid:uuidtemp,name:folderName},function(jsonData){
					 
					 if(jsonData.success){
						
						var tename = folderName;
						input.remove();
						element.find("span").html(tename);
						
						 
						if(label == tename){
							defindMax = parseInt(defindMax)+ 1;
							$('#fileMoveList').attr("defindMax",defindMax);
						}
						//site_tip.setContent("创建文件夹成功",false,true);
						var folder = jsonData.data;
						
						$('#fileMoveList').tree('removeNode', node);
						
						$('#fileMoveList').tree(
			                'appendNode',
			                {
			                    label: folder.name,
			                    id: folder.id
			                },
			                parent_node
			            );
						var lastTitle = $("#folderPath").find("span[hasLast='true']");
						var file_id = lastTitle.attr("uuid");
						if(file_id == undefined){
							file_id = "0";
						}
						if(selectId != file_id){
							isCom = true;
							return;
						}
						var wfcArr = $("#waterfall").find(".wfc");
						var firstIndex = parseInt(wfcArr.first().attr("f-index"));	
						var lastIndex = parseInt(wfcArr.last().attr("f-index"));	
						var index = 0;
						if(firstIndex > lastIndex){
							index = firstIndex + 1;
						}else{
							if(isNaN(lastIndex)){
								lastIndex = 0;
							}
							index = lastIndex + 1;
						}

						 var view = {"data":[{
							 "index" : index,
							 "name":folderName,
							 "created_ts":comm.formatDate(folder.creation_ts),
							 "id":folder.id
						 }]};

						 var item_text = Mustache.to_html(folderItemTpl, view);

						 $("#waterfall").prepend(item_text);
						 $("#selAllFiles").find(".icon-checkbox").removeClass("hover");
						 isCom = true;
						
					 }
					 else
					 {
						 site_tip.setContent(jsonData.message,true,false);
						 $(inputThat).focus();
					 }
					
				 });
		 		 return false;
			 });
			 
			 
			
		});
		
		$('#fileMoveList').bind(
		    'tree.select',
		    function(event) {
		        if (event.node) {
					that.enableAddBtn();
		            // node was selected
		            var node = event.node;
		            //$("#fileMove .btn.ok").attr();
		            var is_selected = $('#fileMoveList').tree('isNodeSelected', node);
					//搜索状态下可以按下
					var isnot_search = $("#search-detail").is(":hidden");
		            if(is_selected){
		            	var element = $(node.element);
		            	if(element.find("input").size()>0){
		            		return;
		            	}
		            	selectId = node.id;
						var params={file_id:selectId};

						var curFolder = $("#folderPath").find("[uuid][haslast]").attr("uuid") || 0;
						if ((selectId!=curFolder) || !isnot_search)
						{
							that.enableOkBtn();
						}
						else
						{
							that.disableOkBtn();
						}
						$.getJSON("/files/get_new_folder_num",params,function(jsonData){
							if(jsonData.success){
								var arr = jsonData.data;
								$("#fileMoveList").attr("defindMax",parseInt(arr.defindMax));
							}
						});
		            	return false;
		            }
		            
		        }
				else
				{
					that.disableOkBtn();
					that.disableAddBtn();
				}
		    }
		);
		
		
	}
	
	return Move;
});